package com.hup.htts.service.tts.jna;

/**
 * SAPI 使用时抛出的HResult异常
 *
 * @author hugan
 * @date 2020/10/16
 */
public class SAPIHResultException extends Exception {

    @SuppressWarnings("SpellCheckingInspection")
    public enum HResult {
        S_OK(0, "S_OK", "成功"),
        REGDB_E_CLASSNOTREG(-2147221164, "REGDB_E_CLASSNOTREG", "未安装语音运行库"),
        NONE_SET_VOICE(-2147024891, "没找到c中的定义值", "未指定语音引擎"),
        E_INVALID_ARG(-2147200967, "E_INVALIDARG", "入参异常"),//如setVoice传入错误值
        UNKNOWN(-1, "UNKNOWN", "未知错误")
        ;

        public final int val;
        public final String enMsg;
        public final String chMsg;

        HResult(int val, String enMsg, String chMsg) {
            this.val = val;
            this.enMsg = enMsg;
            this.chMsg = chMsg;
        }

        /**
         * @param hResult DirectInputApi的调用结果
         * @return 是否成功
         */
        public static boolean succeeded(int hResult) {
            return hResult >= 0;
        }

        /**
         * @param hResult DirectInputApi的调用结果
         */
        public static String getErrMsg(int hResult) {
            for (HResult hr : HResult.values()) {
                if (hr.val == hResult) {
                    return hr.chMsg;
                }
            }
            return "未知异常:" + hResult;
        }

        public static HResult getResult(int hResult) {
            for (HResult hr : HResult.values()) {
                if (hr.val == hResult) {
                    return hr;
                }
            }
            return UNKNOWN;
        }
    }

    public final int hResult;

    public SAPIHResultException(int hResult) {
        super(HResult.getErrMsg(hResult));
        this.hResult = hResult;
    }

    public static void testThrow(int hResult) throws SAPIHResultException {
        if (HResult.succeeded(hResult)) return;

        SAPIHResultException err = new SAPIHResultException(hResult);
        //去掉本方法的记录
        StackTraceElement[] stackTrace = err.getStackTrace();
        StackTraceElement[] reset = new StackTraceElement[stackTrace.length - 1];
        System.arraycopy(stackTrace, 1, reset, 0, reset.length);
        err.setStackTrace(reset);
        throw err;
    }

}
